/**
 * Created by LMN on 2016/7/20.
 */
var express = require('express');
var router = express.Router();
var db = require('../mod/seq.js');
var err = require('../mod/err.js');
var excel = require('../mod/excel.js');
var fs = require("fs");
var config = require('../config');

var _date_format_s = function(obj){
    if(typeof(obj)=='string'){
        return new Date(obj);
    }else{
        var t = new Date(obj);
        return t.getFullYear()+'-'+((t.getMonth()+1)>9?(t.getMonth()+1):('0'+(t.getMonth()+1)))+'-'+
            (t.getDate()>9?t.getDate():('0'+t.getDate()))+' '+(t.getHours()>9?t.getHours():('0'+t.getHours()))+':'+
            (t.getMinutes()>9?t.getMinutes():('0'+t.getMinutes()))+':'+
            (t.getSeconds()>9?t.getSeconds():('0'+t.getSeconds()));
    }
};

// Make and download an excel file.
router.get('/station/:code',function(req, res){
    var start = req.query.start? new Date(req.query.start): null;
    var end = req.query.end? new Date(req.query.end): null;
    var type = req.query.type;
    if(!start||!end||!start.getTime()||!end.getTime()||!type){res.json(err.not_enough_para);return;}
    var conf ={cols: [],rows: []};
    db.station.findOne({ where: { code: req.params.code} }).then(function(stat){
        if(!stat){res.json(err.station_not_exist);return;}
        db.station.findOne({where: req.where({code: req.params.code})}).then(function(station){
            if(!station){res.json(err.no_auth);return;}
            db.find(type,req.params.code,{where: {time: {gt: start,lt: end}}},function(msg){
                if(!msg||msg.length==0) { res.json(err.no_data);return; }
                for(var key in msg[0].dataValues){
                    var colomn = '';
                    if(key == 'id') continue;
                    else if(key == 'time') colomn = '北京时间';
                    else if(key == 'state') colomn = '状态';
                    else if(key == 'mark') colomn = '标记';
                    else if(key == 'model') colomn = '定位模式';
                    else if(key == 'accuracy') colomn = '坐标精度(毫米)';
                    else if(key == 'n') colomn = '南北偏移(米)';
                    else if(key == 'e') colomn = '东西偏移(米)';
                    else if(key == 'u') colomn = '高程偏移(米)';
                    else if(key == 'a_n') colomn = '纬度';
                    else if(key == 'a_e') colomn = '经度';
                    else if(key == 'a_u') colomn = '高程(米)';
                    else if(key == 'stationCode') continue;
                    conf.cols.push({caption: colomn+'', type: 'string'})
                }
                for( var i= 0,l=msg.length;i<l;i++){
                    conf.rows[i] = [];
                    for(var key2 in msg[i].dataValues){
                        var value = msg[i].dataValues[key2]+'';
                        if(key2 == 'id') continue;
                        else if(key2 == 'stationCode') continue;
                        else if(key2 == 'mark'){
                            if(value == '0') value = '单BDS解算';
                            else if(value == '1') value = '单GPS解算';
                            else if(value == '2') value = 'BDS+GPS解算';
                        }else if(key2 == 'model'){
                            if(value == '0') value = '实时解算';
                            else if(value == '1') value = '后处理解算';
                            else if(value == '2') value = '均值滤波';
                            else if(value == '3') value = '最小二乘滤波';
                            else if(value == '4') value = '最优滤波';
                        }else if(key2 == 'state'){
                            if(value == config.def_state.disconnect+'') value = '离线';
                            else if(value == config.def_state.normal+'') value = '正常';
                            else if(value == config.def_state.repaired+'') value = '维修完成';
                            else if(value == config.def_state.repairing+'') value = '维修中';
                            else if(value == config.def_state.disaster+'') value = '故障';
                            else if(value == config.def_state.alarm+'') value = '预警';
                        }else if(key2 == 'time'){
                            value = _date_format_s(new Date(value));
                        }
                        conf.rows[i].push(value);
                    }
                }
                var filename = req.params.code+".xlsx";
                res.setHeader('Content-Disposition', 'attachment; filename='+encodeURIComponent(filename));
                excel.createExcel({
                    data:conf,
                    cb:function(path){
                        res.download(path, filename, function(){
                            fs.unlink(path);
                        });
                    }
                });
            });
        });
    });
});
module.exports = router;